/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.prepare;

import cn.ac.nercis.pes.common.constant.evaluation.EvaluationModule;
import cn.ac.nercis.pes.common.constant.project.FinishState;
import cn.ac.nercis.pes.community.component.dialog.*;
import cn.ac.nercis.pes.community.component.spreadsheet.prepare.SecurityThreatSheetView;
import cn.ac.nercis.pes.community.controller.base.GlobalEventHandle;
import cn.ac.nercis.pes.community.controller.base.InitEvalDataLoad;
import cn.ac.nercis.pes.community.manager.RealTimeSaveManager;
import cn.ac.nercis.pes.community.mapper.evaluation.SecurityThreatViewMapper;
import cn.ac.nercis.pes.community.utils.*;
import cn.ac.nercis.pes.community.views.evaluation.prepare.PrepareView;
import cn.ac.nercis.pes.model.dto.evaluation.prepare.SecurityThreatDTO;
import cn.ac.nercis.pes.service.evaluation.SecurityThreatService;
import javafx.application.Platform;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.concurrent.CompletableFuture;

/**
 * 安全威胁管理控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class SecurityThreatController implements Initializable, GlobalEventHandle, InitEvalDataLoad {

    @FXML
    private StackPane page;
    @FXML
    private Button saveButton;
    @FXML
    private Button tmpSaveButton;
    @FXML
    private SecurityThreatSheetView sheetView;

    private String currentSystemId;

    protected final SimpleBooleanProperty dataSaving = new SimpleBooleanProperty(false);
    private final SecurityThreatService securityThreatService;
    private final RealTimeSaveManager realTimeSaveManager = new RealTimeSaveManager(this::realTimeSave);

    public SecurityThreatController() {
        this.securityThreatService = SpringUtils.getBean(SecurityThreatService.class);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        saveButton.setGraphic(IconUtils.getGlyph("save-button-icon","btn-icon"));
        tmpSaveButton.setGraphic(IconUtils.getGlyph("temp-save-button-icon","btn-icon"));
        saveButton.disableProperty().bind(dataSaving);
        tmpSaveButton.disableProperty().bind(dataSaving);
        GuiStore.applyQuickSave(this.page,this::onGlobalSave);
        realTimeSaveManager.listenerSheetChange(this.sheetView);
    }

    @Override
    public void initializeData(String systemId){
        LogUtils.info(log, "初始化安全威胁信息...");
        this.currentSystemId = systemId;
        this.sheetView.initialize(systemId,this::onDeleteSecurityThreat);
        this.querySecurityThreat();
    }

    @Override
    public void onGlobalSave() {
        LogUtils.info(log, "执行快捷保存操作...");
        batchSave(false,false);
    }

    @FXML
    public void onTmpSave(){
        LogUtils.info(log, "执行暂存操作...");
        this.batchSave(false,false);
    }

    @FXML
    public void onFinishSave(){
        LogUtils.info(log, "执行保存操作...");
        this.batchSave(false,true);
    }

    public void realTimeSave(){
        LogUtils.info(log, "执行即时保存操作...");
        this.batchSave(true,false);
    }

    private void onDeleteSecurityThreat(Set<String> ids){
        LogUtils.info(log, "执行删除操作...");
        if(CollectionUtils.isEmpty(ids)){
            return;
        }
        AlertDialog alertDialog = AlertDialog.builder()
                .withMode(AlertMode.CONFIRM)
                .withType(AlertType.WARN)
                .withTitle("删除提示")
                .withContent("确认删除当前自定义的安全威胁信息吗？")
                .withContainer(this.page)
                .build();
        alertDialog.show((confirm)->{
            if(!confirm){
                return;
            }
            deleteSecurityThreat(ids);
        });
    }

    private void deleteSecurityThreat(final Set<String> ids) {
        LogUtils.info(log, "删除自定义的安全威胁信息...");
        LogUtils.info(log, "请求数据：{}", ids);
        CompletableFuture.supplyAsync(() -> this.securityThreatService.batchDeleteSecurityThreat(ids))
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        //更新表数据
                        this.querySecurityThreat();
                        MessageDialog.builder()
                                .withContainer(this.page)
                                .withType(MessageType.SUCCESS).withMessage("删除成功")
                                .build().show();
                        refreshFinishProcess(false);
                    } else {
                        MessageDialog.builder()
                                .withContainer(this.page)
                                .withType(MessageType.FAIL).withMessage(res.getMsg())
                                .build().show();
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("删除自定义安全威胁信息出错!", ex);
                    return null;
                });
    }

    private void batchSave(boolean realTime,boolean finish){
        if(!this.sheetView.validate()){
            if(!realTime){
                AppUtils.showMessageDialog("以下标出的自定义安全威胁的必填信息不能为空",MessageType.WARN,this.page);
            }
            return;
        }
        List<SecurityThreatDTO> securityThreats = this.sheetView.getModifyData().stream()
                .map(SecurityThreatViewMapper.INSTANCE::toThreatDTO)
                .toList();
        if (!realTime && CollectionUtils.isEmpty(securityThreats)) {
            AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
            refreshFinishProcess(finish);
            return;
        }
        this.dataSaving.setValue(true);
        LogUtils.info(log, "批量保存自定义威胁信息...");
        LogUtils.record(log, "请求数据：{}", securityThreats);
        //未保存的数据进行批量保存
        CompletableFuture.supplyAsync(() -> this.securityThreatService.batchSaveSecurityThreat(securityThreats))
                .thenAccept(res -> Platform.runLater(() -> {
                    this.dataSaving.setValue(false);
                    if (res.isSuccess()) {
                        //更新表数据
                        this.querySecurityThreat();
                        if(!realTime){
                            AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
                        }
                        refreshFinishProcess(finish);

                    } else {
                        if(realTime){
                            log.error("即时保存自定义威胁信息失败：{}",res.getMsg());
                        }else{
                            AppUtils.showMessageDialog(res.getMsg(),MessageType.FAIL,this.page);
                        }
                    }
                }))
                .exceptionally((ex) -> {
                    this.dataSaving.setValue(false);
                    log.error("批量保存自定义威胁信息出错!", ex);
                    return null;
                });
    }

    private void querySecurityThreat() {
        LogUtils.info(log, "获取安全威胁信息...");
        LogUtils.info(log, "请求数据：{}", this.currentSystemId);
        CompletableFuture.supplyAsync(() -> this.securityThreatService.findSecurityThreat(this.currentSystemId))
                .thenAccept(res -> Platform.runLater(() -> {
                    var data = res.stream()
                            .map(SecurityThreatViewMapper.INSTANCE::toThreatVO)
                            .toList();
                    this.sheetView.loadContent(data);
                }))
                .exceptionally((ex) -> {
                    log.error("获取自定义威胁信息出错!", ex);
                    MessageDialog.builder()
                            .withContainer(this.page)
                            .withType(MessageType.FAIL).withMessage("加载安全威胁信息失败！")
                            .build().show();
                    return null;
                });
    }

    private void refreshFinishProcess(boolean finish){
        var prepareView = AppStore.getEvaluationView(this.currentSystemId, PrepareView.class);
        if(prepareView.getController() instanceof PrepareController controller){
            controller.setEvalProcess(EvaluationModule.SECURITY_THREAT, finish ? FinishState.FINISH:FinishState.INCOMPLETE);
        }
    }
}